package com.lc.utils;

import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.FileOutputStream;
import java.net.URL;
import java.util.List;

public class InsertImageToPdf {

    /**
     * * @param insertPage 插入的页码 从1开始
     * * @param insertX    插入位置 左边距 （起点为左下角）
     * * @param insertY    插入位置 底边距 （起点为左下角）
     * * @param picWidth   插入图片的宽度
     * * @param picHeight  插入图片的高度
     */
    public static class InsertPicInfo {
        public String imagePath;
        public int insertPage;
        public int insertX;
        public int insertY;
        public int picWidth;
        public int picHeight;
        public float picRotate = 0f;
    }

    /**
     * insert multiple images to pdf document
     *
     * @param source     源文件
     * @param insertInfos 插入图片的信息列表
     * @param targetPath 输出文件位置
     * @throws Exception
     */
    public static void signPdfByStampKeyNocertMultiplePics(Object source, String targetPath,
                                                           List<InsertPicInfo> insertInfos ) throws Exception {
// 读取模板文件
        PdfReader reader = null;
        if (source instanceof String) {
            reader = new PdfReader((String) source);
        } else if (source instanceof byte[]) {
            reader = new PdfReader((byte[]) source);
        } else if (source instanceof URL) {
            reader = new PdfReader((URL) source);
        }

        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPath));

        for (int i = 0; i < insertInfos.size(); i++) {
            InsertPicInfo tempInfo = insertInfos.get(i);
            PdfContentByte overContent = stamper.getOverContent(tempInfo.insertPage);

            Image image = Image.getInstance(tempInfo.imagePath);
            image.scaleToFit(tempInfo.picWidth, tempInfo.picHeight);
            image.setAbsolutePosition(tempInfo.insertX, tempInfo.insertY);

            image.setRotationDegrees(tempInfo.picRotate);// 旋转 角度

            overContent.addImage(image);
            overContent.stroke();
        }

        stamper.close();
        reader.close();

        return;
    }
}
